package com.zh.utils;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

public class Dowload {


    //导出excel
    public static void dowload(HttpServletResponse response, List<String> titleList, List<List<String>>contentList){

        System.out.println("title - "+titleList);
        System.out.println("contentList -- "+contentList);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-download");

        //定义文件名
        String fileName = "D://myExcel.xlsx";
        try {
            fileName = URLEncoder.encode(fileName,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

        System.out.println("11111");
        // 第一步：定义一个新的工作簿
        XSSFWorkbook wb = new XSSFWorkbook();
        // 第二步：创建一个Sheet页
        XSSFSheet mySheet = wb.createSheet("mySheet1");

        System.out.println("22222");
        //定义第一行(标题行)
        XSSFRow titleRow = mySheet.createRow(0);
        for(int i=0;i<titleList.size();i++){
            XSSFCell titleCell = titleRow.createCell(i);//定义第1行第i列
            titleCell.setCellValue(titleList.get(i));
        }

        System.out.println("33333");
        for(int i=0;i<contentList.size();i++){
            XSSFRow contentRow = mySheet.createRow(i+1); //定义第i行
            List<String> fieldList =  contentList.get(i);
            for(int j=0;j<fieldList.size();j++){
                XSSFCell contentCell = contentRow.createCell(j);//定义第行第i列
                contentCell.setCellValue(fieldList.get(j));
            }
        }

        System.out.println("44444");
        //输出此excel
        try {
            OutputStream out = response.getOutputStream();
            wb.write(out);
            out.close();
            wb.close();
            System.out.println("dowload___yes");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
